package ua.kiev.tosik.price.modules.clients.conf;

import org.apache.log4j.Logger;
import org.w3c.dom.*;
import ua.kiev.tosik.price.conf.AppConfig;
import ua.kiev.tosik.price.modules.clients.models.FilterAction;
import ua.kiev.tosik.price.modules.clients.tools.IPriceValidator;

import javax.swing.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.util.Vector;

public class FilterConfig {

	private static FilterConfig ourInstance;
	private static Logger logger = Logger.getLogger("ua.kiev.tosik.price.modules.clients.conf");
	private final String xmlConfig;
	private final String lang;
	private final Vector<FilterAction> filters;

	public static FilterConfig getInstance() {
		if (ourInstance == null) {
			ourInstance = new FilterConfig();
		}
		return ourInstance;
	}

	private FilterConfig() {
		logger.debug("Initialize FilterConfig");
		xmlConfig = "conf/filters.xml";
		filters = new Vector<FilterAction>();
		lang = AppConfig.getInstance().get("app.language");
		try {
			loadConfig();
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
	}

	private void loadConfig() throws Exception {
		logger.debug("Try to load prices filters...");
		File file = new File(xmlConfig);
		if ( !file.exists() ) {
			logger.error("Filter config file [" + xmlConfig + "] was not found!");
			return;
		}
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		Document doc = db.parse(file);
		doc.getDocumentElement().normalize();
		NodeList nodeLst = doc.getElementsByTagName("action");
		for (int s = 0; s < nodeLst.getLength(); s++) {
			Node fstNode = nodeLst.item(s);
			if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
				NamedNodeMap attrList = fstNode.getAttributes();
				String id = attrList.getNamedItem("id").getNodeValue();
				String required = attrList.getNamedItem("required").getNodeValue();
				NodeList name = ((Element) fstNode).getElementsByTagName("name-" + lang);
				NodeList validatorClass = ((Element) fstNode).getElementsByTagName("validator-class");
				NodeList icon = ((Element) fstNode).getElementsByTagName("icon");
				FilterAction filterAction = new FilterAction();
				filterAction.setId(id);
				filterAction.setName(name.item(0).getTextContent().trim());
				filterAction.setIcon( new ImageIcon(icon.item(0).getTextContent().trim()) );
				filterAction.setRequired(Boolean.valueOf(required));
				if ( validatorClass != null && !validatorClass.item(0).getTextContent().trim().equals("") ) {
					Class clazz = Class.forName(validatorClass.item(0).getTextContent().trim());
					IPriceValidator validator = (IPriceValidator)clazz.getConstructor().newInstance();
					filterAction.setValidator(validator);
				}
				filters.add(filterAction);
			}
		}
	}

	public Vector<FilterAction> getFilters() {
		return filters;
	}
}
